//
//  WFCUPostDynamicVC.m
//  WFChatUIKit
//
//  Created by 0000 on 2024/5/31.
//  Copyright © 2024 Tom Lee. All rights reserved.
//

#import "WFCUPostDynamicVC.h"

#import "MBProgressHUD.h"
#import "WFCUImage.h"
#import "WFCUUtilities.h"
#import "UIView+Toast.h"


#import "YGExtendChain.h"
#import "SDAutoLayout.h"
#import <WFChatClient/WFCChatClient.h>
#import "AFNetworking.h"



#import <ZLPhotoBrowser/ZLPhotoBrowser-Swift.h>
#import <Photos/Photos.h>
#import "MBProgressHUD.h"
#import "UIView+Toast.h"
#import "WFCUConfigManager.h"

#import "WFCULocationViewController.h"
#import "WFCULocationPoint.h"
#import "YGExtendChain.h"

#import "WFCUContactListViewController.h"



@interface WFCUPostDynamicVC ()<UITextViewDelegate,LocationViewControllerDelegate>

@property(nonatomic, strong)UIScrollView *scrollView;

@property(nonatomic, strong)UITextView *textView;
@property (nonatomic, strong)NSMutableArray *images,*managerList;
@property (nonatomic, strong)UIView *imgViews;
@property (nonatomic, strong)NSString *desFileName;
@property (nonatomic, strong)UILabel *placeholderLabel;

@property (nonatomic, strong)WFCULocationPoint *locationPoint;
@property (nonatomic, strong)UIButton *btn1,*btn3;
@property (nonatomic, strong)UIView * popView ;
@property (nonatomic, strong)UILabel *btn3L;


@property (nonatomic, assign)int selectsT ;

@end

@implementation WFCUPostDynamicVC
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [self initDATA];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.scrollView = [[UIScrollView alloc]init];
    
    [self.view addSubview:self.scrollView];
    self.scrollView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(ZmNavigationHeight_N(), 0, 0, 0));
    
    
    self.textView = [[UITextView alloc] init];
//    self.textView.editable = NO;
//    self.textView.text = self.announcement.text;
    self.textView.font = [UIFont systemFontOfSize:16];
    self.textView.delegate = self;
    
    [self.scrollView addSubview:self.textView];
    self.textView.sd_layout.leftSpaceToView(self.scrollView, 20).topSpaceToView(self.scrollView, 0 ).widthIs(ZmScreenWidth_N() - 40).heightIs(100);
    
    
    //占位文字
    UILabel *placeholderLabel = [[UILabel alloc] init];
    placeholderLabel.text = @"写下这一刻你的感受与想法吧！";
    placeholderLabel.textColor = [UIColor colorWithHexExtendString:@"#797979"];
    placeholderLabel.font = self.textView.font;
    placeholderLabel.backgroundColor = [UIColor clearColor];
    [self.textView addSubview:placeholderLabel];
    placeholderLabel.sd_layout.leftSpaceToView(self.textView, 4).topSpaceToView(self.textView, 8).autoHeightRatio(0);
    [placeholderLabel setSingleLineAutoResizeWithMaxWidth:290];
    self.placeholderLabel = placeholderLabel ;
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self.textView];


    self.imgViews = [[UIView alloc]init];
    [self.scrollView addSubview:self.imgViews];
    self.imgViews.sd_layout.leftSpaceToView(self.scrollView, 20).heightIs(55).widthIs(ZmScreenWidth_N() - 40).topSpaceToView(self.textView, 20).heightIs(1);

    WEAKSELF_ZM
    
    
    UIButton *btn1 = [[UIButton alloc]init];
    
    [self.scrollView addSubview:btn1];
    btn1.sh_chain_extend.image_loc(@"circle_post_1").title(@"所在位置").font_size(14).titleInsets(UIEdgeInsetsMake(0, 20, 0, 0)).titleColorBlack().contentHorizontalAlignment(UIControlContentHorizontalAlignmentLeft);
    btn1.sd_layout.leftSpaceToView(self.scrollView, 20).heightIs(55).widthIs(ZmScreenWidth_N() - 40).topSpaceToView(self.imgViews, 20);
    
    UIView *line1 = [[UIView alloc]init];
    line1.backgroundColor = [UIColor colorWithHexExtendString:@"#D8D8D8"];
    [btn1 addSubview:line1];
    line1.sd_layout.leftEqualToView(btn1).bottomEqualToView(btn1).rightEqualToView(btn1).heightIs(1);
    
    [btn1 jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
       
        [weakSelf.view endEditing:YES];
        
        WFCULocationViewController *vc = [[WFCULocationViewController alloc] initWithDelegate:weakSelf];
        
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
        [weakSelf presentViewController:nav animated:YES completion:nil];
        
        
        
    }];
    
    
    
    self.btn1 = btn1;
    
    
    
    
    
//    UIButton *btn2 = [[UIButton alloc]init];
//    
//    [self.scrollView addSubview:btn2];
//    btn2.sh_chain_extend.image_loc(@"circle_post_2").title(@"提醒谁看").font_size(14).titleInsets(UIEdgeInsetsMake(0, 20, 0, 0)).titleColorBlack().contentHorizontalAlignment(UIControlContentHorizontalAlignmentLeft);
//    btn2.sd_layout.leftSpaceToView(self.scrollView, 20).heightIs(55).widthIs(ZmScreenWidth_N() - 40).topSpaceToView(btn1, 1);
//    
//    UIView *line2 = [[UIView alloc]init];
//    line2.backgroundColor = [UIColor colorWithHexExtendString:@"#D8D8D8"];
//    [btn2 addSubview:line2];
//    line2.sd_layout.leftEqualToView(btn2).bottomEqualToView(btn2).rightEqualToView(btn2).heightIs(1);
//    
//    
//    
//    
//    
//    
//    
//    
//    
//    
//    
//    
//    
//    
    UIButton *btn3 = [[UIButton alloc]init];
    
    [self.scrollView addSubview:btn3];
    btn3.sh_chain_extend.image_loc(@"circle_post_3").title(@"谁可以看").font_size(14).titleInsets(UIEdgeInsetsMake(0, 20, 0, 0)).titleColorBlack().contentHorizontalAlignment(UIControlContentHorizontalAlignmentLeft).addTarget_action(self, @selector(postDynamic));
    btn3.sd_layout.leftSpaceToView(self.scrollView, 20).heightIs(55).widthIs(ZmScreenWidth_N() - 40).topSpaceToView(btn1, 1);
    
    UIView *line3 = [[UIView alloc]init];
    line3.backgroundColor = [UIColor colorWithHexExtendString:@"#D8D8D8"];
    [btn3 addSubview:line3];
    line3.sd_layout.leftEqualToView(btn3).bottomEqualToView(btn3).rightEqualToView(btn3).heightIs(1);
//    
    self.btn3 = btn3;
    
    
    
    UIImageView *right_arrow = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"right_arrow"]];
    [btn3 addSubview:right_arrow];
    right_arrow.sd_layout.centerYEqualToView(btn3).rightSpaceToView(btn3, 12).heightIs(16).widthIs(16);
    
    
    
    
    UILabel *btn3L = [[UILabel alloc] init];
    btn3L.font = [UIFont systemFontOfSize:14];
    btn3L.backgroundColor = [UIColor clearColor];
    [btn3 addSubview:btn3L];
    btn3L.sd_layout.centerYEqualToView(btn3).rightSpaceToView(right_arrow, 6).autoHeightRatio(0);
    [btn3L setSingleLineAutoResizeWithMaxWidth:ZmScreenWidth_N()/2];
    self.btn3L = btn3L;
    btn3L.sh_chain_extend.title(@"开放").titleColor([UIColor colorWithHexExtendString:@"#636363"]);

    
    [self.scrollView setupAutoContentSizeWithBottomView:btn3 bottomMargin:0];
    
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:WFCString(@"发布") style:UIBarButtonItemStyleDone target:self action:@selector(onSaveBtn:)];

    
    
    
    self.managerList = @[].mutableCopy;
    self.selectsT = 1;
    
 
    
}
 
- (void)initDATA{
    
    
    if (!self.photos.count) {
         
        self.photos = @[].mutableCopy;

        
        
    }
    if(self.videoUrl){
        
        
//        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
//                                                             NSUserDomainMask, YES);
//        NSString *documentDirectory = [paths objectAtIndex:0];
//
//
//        NSData *data = [[NSData alloc] initWithContentsOfURL:self.videoUrl];
//
//        NSString *desFileName = [documentDirectory stringByAppendingPathComponent:[self.videoUrl lastPathComponent]];
//        [data writeToFile:desFileName atomically:YES];
//        self.desFileName = desFileName;
//
//        UIImage *thumb = [self getVideoThumbnailWithUrl:self.videoUrl second:1];
//
//        self.images = @[thumb].mutableCopy;
 
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [MBProgressHUD HUDForView:self.view].mode = MBProgressHUDModeDeterminate;
            [MBProgressHUD HUDForView:self.view].label.text = WFCString(@"Processing");
        });
        
        [self handleVideo:self.videoUrl photos:@[] isFullImage:YES];

//        AVURLAsset * asset = [AVURLAsset assetWithURL:self.videoUrl];
//        CMTime   time = [asset duration];
//        int seconds = ceil(time.value/time.timescale);
        
//            [self videoDidCapture:desFileName thumbnail:thumb duration:seconds];
        
//        NSURL *videoUrl = [NSURL URLWithString:desFileName];
//        AVURLAsset *avUrl = [AVURLAsset assetWithURL:videoUrl];
//            CMTime time = [avUrl duration];
//          int duration = ceil(time.value/time.timescale);

        
//        [self reloadImagesViews];
        
    }else if (self.photos.count){
        self.images = @[].mutableCopy;
        [self recursiveHandle:[NSMutableArray arrayWithArray:self.photos] isFullImage:YES];
        
    }
    
}
- (void)postDynamic{
    
//    WFCUPostDynamicVC *vc = [[WFCUPostDynamicVC alloc]init];
//
//    [self.navigationController pushViewController:vc animated:YES];
    
    [self.view endEditing:YES];
    
    self.popView.alpha = 0 ;
    [([UIApplication sharedApplication].keyWindow ?: [UIApplication sharedApplication].windows.firstObject) addSubview:self.popView];
    self.popView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));

    
    [UIView animateWithDuration:0.15 animations:^{

        self.popView.alpha = 1 ;

    } completion:^(BOOL finished) {
       

    }];
    
    
}


- (UIView *)popView{
   if (!_popView) {
       _popView = [[UIView alloc]init];
       
       _popView.sh_chain_extend.backgroundColor([UIColor colorWithHexExtendString:@"#3F3C41" alpha:0.57]).addTarget_action(self, @selector(removeMain));

       UIView *view = [[UIView alloc]init];
       [_popView addSubview:view];
       view.sd_layout.centerXEqualToView(self.view).bottomEqualToView(self.view).offset(30).heightIs(60 * 5 + 60).widthIs(ZmScreenWidth_N()  ) ;
       view.sh_chain_extend.backgroundColorWhite().roundSize(20);

       
       
     
       
//       NSDictionary *attributes = @{
//           NSForegroundColorAttributeName: [UIColor colorWithHexExtendString:@"#797979"],
//           NSFontAttributeName: [UIFont systemFontOfSize:12]
//       };
//       NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:attributes];
       
 
       

       UIButton *btn1 = [[UIButton alloc]init];
       [view addSubview:btn1];
       btn1.sh_chain_extend.font_size(16).titleColorBlack().title(@"开放").addTarget_action(self, @selector(on1Register));
       btn1.sd_layout.leftSpaceToView(view, 20).heightIs(60).widthIs(ZmScreenWidth_N() - 40).topSpaceToView(view, 10);
 
       UIView *line1 = [[UIView alloc]init];
       line1.backgroundColor = [UIColor colorWithHexExtendString:@"#D8D8D8"];
       [btn1 addSubview:line1];
       line1.sd_layout.leftEqualToView(btn1).bottomEqualToView(btn1).rightEqualToView(btn1).heightIs(1);
       
        
       
//       1开放，2私密，3部分可见，4不给谁看


       
       
       
       
       UIButton *btn2 = [[UIButton alloc]init];
       
       [view addSubview:btn2];
       btn2.sh_chain_extend.title(@"私密").font_size(16).titleColorBlack().addTarget_action(self, @selector(on2Register));
       btn2.sd_layout.leftSpaceToView(view, 20).heightIs(60).widthIs(ZmScreenWidth_N() - 40).topSpaceToView(view, 70);
       
       UIView *line2 = [[UIView alloc]init];
       line2.backgroundColor = [UIColor colorWithHexExtendString:@"#D8D8D8"];
       [btn2 addSubview:line2];
       line2.sd_layout.leftEqualToView(btn2).bottomEqualToView(btn2).rightEqualToView(btn2).heightIs(1);
       
       

    
       
       UIButton *btn3 = [[UIButton alloc]init];
       
       [view addSubview:btn3];
       btn3.sh_chain_extend.title(@"部分可见").font_size(16).titleColorBlack().addTarget_action(self, @selector(on3Register));
       btn3.sd_layout.leftSpaceToView(view, 20).heightIs(60).widthIs(ZmScreenWidth_N() - 40).topSpaceToView(btn2, 1);
       
       UIView *line3 = [[UIView alloc]init];
       line3.backgroundColor = [UIColor colorWithHexExtendString:@"#D8D8D8"];
       [btn3 addSubview:line3];
       line3.sd_layout.leftEqualToView(btn3).bottomEqualToView(btn3).rightEqualToView(btn3).heightIs(1);
       
       
       
       
       
       UIButton *btn4 = [[UIButton alloc]init];
       
       [view addSubview:btn4];
       btn4.sh_chain_extend.title(@"不给谁看").font_size(16).titleColorBlack().addTarget_action(self, @selector(on4Register));
       btn4.sd_layout.leftSpaceToView(view, 20).heightIs(60).widthIs(ZmScreenWidth_N() - 40).topSpaceToView(btn3, 1);
       
       UIView *line4 = [[UIView alloc]init];
       line4.backgroundColor = [UIColor colorWithHexExtendString:@"#D8D8D8"];
       [btn4 addSubview:line4];
       line4.sd_layout.leftEqualToView(btn4).bottomEqualToView(btn4).rightEqualToView(btn4).heightIs(1);
       
       
       
       
       
       UIButton *btn5 = [[UIButton alloc]init];
       
       [view addSubview:btn5];
       btn5.sh_chain_extend.title(@"取消").font_size(16).titleColor([UIColor colorWithHexExtendString:@"#016EFF"]);
       btn5.sd_layout.leftSpaceToView(view, 20).heightIs(60).widthIs(ZmScreenWidth_N() - 40).topSpaceToView(btn4, 1);
       WEAKSELF_ZM
    
        [btn5 jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {


            [weakSelf removeMain];

        }];
       
   }
   return _popView;
}
 
- (void)on1Register  {
    [self removeMain];
    self.selectsT = 1;
    self.btn3L.sh_chain_extend.title(@"开放").titleColor([UIColor colorWithHexExtendString:@"#636363"]) ;
    self.btn3.sh_chain_extend.title(@"谁可以看");
    self.managerList = @[].mutableCopy;

}
- (void)on2Register  {
   [self removeMain];
    self.selectsT = 2;
    self.btn3L.sh_chain_extend.title(@"私密").titleColor([UIColor colorWithHexExtendString:@"#636363"]) ;
    self.btn3.sh_chain_extend.title(@"谁可以看");
    self.managerList = @[].mutableCopy;
    
}
//       1开放，2私密，3部分可见，4不给谁看

- (void)on3Register  {
   [self removeMain];
    self.selectsT = 3;
    WEAKSELF_ZM
    
//    [self selectMemberToAdd];

    NSMutableArray *names = @[].mutableCopy;
    NSMutableArray *ids = @[].mutableCopy;

    WFCUContactListViewController *pvc = [[WFCUContactListViewController alloc] init];
    pvc.selectContact = YES;
    pvc.multiSelect = YES;
    __weak typeof(self)ws = self;
    pvc.selectResult = ^(NSArray<NSString *> *contacts) {
//        [[WFCCIMService sharedWFCIMService] setGroupManager:self.groupInfo.target isSet:YES memberIds:contacts notifyLines:@[@(0)] notifyContent:nil success:^{
            for (NSString *memberId in contacts) {
                WFCCUserInfo *member = [[WFCCIMService sharedWFCIMService] getUserInfo:memberId refresh:NO];
                if (member) {

                    [ids addObject:member.userId];
                    [names addObject:member.displayName];
                     
                }
            }
            if (contacts.count) {
//                [ws.tableView reloadData];
                ws.managerList = ids;
                
                
                ws.btn3.sh_chain_extend.title(@"部分可见");
                ws.btn3L.sh_chain_extend.title([NSString stringWithFormat:@"%@",[names componentsJoinedByString:@","]]).titleColor([UIColor colorWithHexExtendString:@"#016EFF"]);

                
            }
//        } error:^(int error_code) {
//
//        }];
    };
//    NSMutableArray *candidateUsers = [[NSMutableArray alloc] init];
    NSArray *memberList = [[WFCCIMService sharedWFCIMService] getMyFriendList:NO];
 
    if([memberList count]) {
        pvc.candidateUsers = memberList;
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:pvc];
        [self.navigationController presentViewController:navi animated:YES completion:nil];
    } else {
//        [self.view makeToast:@"成员已全部添加"];
    }
    
}
- (void)on4Register  {
   [self removeMain];
    WEAKSELF_ZM
    self.selectsT = 4;
    [self selectMemberToAdd];

//    self.btn3.sh_chain_extend.title(@"私密").titleColor([UIColor colorWithHexExtendString:@"#016EFF"]);
    self.managerList = @[].mutableCopy;
    NSMutableArray *names = @[].mutableCopy;
    NSMutableArray *ids = @[].mutableCopy;
    
    WFCUContactListViewController *pvc = [[WFCUContactListViewController alloc] init];
    pvc.selectContact = YES;
    pvc.multiSelect = YES;
    __weak typeof(self)ws = self;
    pvc.selectResult = ^(NSArray<NSString *> *contacts) {
//        [[WFCCIMService sharedWFCIMService] setGroupManager:self.groupInfo.target isSet:YES memberIds:contacts notifyLines:@[@(0)] notifyContent:nil success:^{
            for (NSString *memberId in contacts) {
                WFCCUserInfo *member = [[WFCCIMService sharedWFCIMService] getUserInfo:memberId refresh:NO];
                if (member) {

                    [ids addObject:member.userId];
                    [names addObject:member.displayName];
                     
                }
            }
            if (contacts.count) {
//                [ws.tableView reloadData];
                ws.managerList = ids;
                ws.btn3.sh_chain_extend.title(@"不给谁看");
                ws.btn3L.sh_chain_extend.title([NSString stringWithFormat:@"%@",[names componentsJoinedByString:@","]]).titleColor([UIColor colorWithHexExtendString:@"#016EFF"]);
 
            }
//        } error:^(int error_code) {
//
//        }];
    };
//    NSMutableArray *candidateUsers = [[NSMutableArray alloc] init];
    NSArray *memberList = [[WFCCIMService sharedWFCIMService] getMyFriendList:NO];
 
    if([memberList count]) {
        pvc.candidateUsers = memberList;
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:pvc];
        [self.navigationController presentViewController:navi animated:YES completion:nil];
    } else {
//        [self.view makeToast:@"成员已全部添加"];
    }
}
 
- (void)removeMain
{


  [UIView animateWithDuration:0.15 animations:^{

      self.popView.alpha = 0 ;
  } completion:^(BOOL finished) {
      self.popView.hidden = YES;
      [self.popView removeFromSuperview];
      self.popView  = nil;

  }];
    
}

- (void)selectMemberToAdd {
    
  
}

- (void)onSendLocation:(WFCULocationPoint *)locationPoint{
//    [self.delegate locationDidSelect:locationPoint.coordinate locationName:locationPoint.title mapScreenShot:locationPoint.thumbnail];
    self.locationPoint = locationPoint;
    
    self.btn1.sh_chain_extend.title(locationPoint.title).titleColor([UIColor colorWithHexExtendString:@"#016EFF"]);
    
    
}

//- (void)dealloc{
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}

- (void)textDidChange
{
    if([self.textView.text containsString:@"\n"])
    {
        
        return;
    }
    
}
- (void)reloadImagesViews{
    
    if (self.imgViews.subviews.count) {
         
        [self.imgViews removeAllSubviews];

    }
    
    NSMutableArray *list = [NSMutableArray array];
    NSInteger select = self.images.count == 9 ? 9 : self.images.count + 1;
    if (self.videoUrl) {
        select = self.images.count ;
    }
    for (int i = 0; i < select; i++) {
         
        
        UIButton *btn3 = [[UIButton alloc]init];
        
        [self.imgViews addSubview:btn3];
        if (self.videoUrl) {
             

            btn3.sh_chain_extend.modeFill().clipsToBounds(YES).roundSize(10).addTarget_action(self, @selector(clickImage:));
            btn3.sd_layout.heightIs(ZmScreenWidth_N()/2 - 20);
            
            
            UIImageView *img = [[UIImageView alloc]initWithImage:[[UIImage imageNamed:@"video_msg_cover"] imageWithChangeColor:[UIColor whiteColor] ]];
            [btn3 addSubview:img];
            img.sd_layout.centerXEqualToView(btn3).centerYEqualToView(btn3).widthIs(40).heightIs(40);
            img.sh_chain_extend.backgroundColorClear();
            
            

        }else{
            btn3.sh_chain_extend.image_loc(@"circle_add").modeFill().clipsToBounds(YES).roundSize(10).addTarget_action(self, @selector(clickImage:));
            btn3.sd_layout.heightIs(ZmScreenWidth_N()/3 - 20);

        }

        if (self.images.count == i) {
             
        }else{
            if (self.images.count) {
                 
                [btn3 setImage:self.images[i] forState:0];

            }
        }
        
        [list addObject:btn3];
        
    }
    
    if (self.videoUrl) {
        [self.imgViews setupAutoWidthFlowItems:list withPerRowItemsCount:2 verticalMargin:10 horizontalMargin:10 verticalEdgeInset:0 horizontalEdgeInset:0];

    }else{
        [self.imgViews setupAutoWidthFlowItems:list withPerRowItemsCount:3 verticalMargin:10 horizontalMargin:10 verticalEdgeInset:0 horizontalEdgeInset:0];

    }
    
    
}
- (void)clickImage:(id)sender {
    
    
    WEAKSELF_ZM
    [weakSelf.view endEditing:YES];

    [ZLPhotoConfiguration default].allowSelectImage = YES;
    [ZLPhotoConfiguration default].allowSelectVideo = YES;
    [ZLPhotoConfiguration default].maxSelectCount = 9;
    [ZLPhotoConfiguration default].allowMixSelect = NO;
    [ZLPhotoConfiguration default].allowTakePhotoInLibrary = NO;
    [ZLPhotoConfiguration default].allowEditImage = YES;
    [ZLPhotoConfiguration default].allowEditVideo = YES;
    //视频最大时长，默认是5分钟，可以更改为更大
    [ZLPhotoConfiguration default].maxSelectVideoDuration = 300;
    [ZLPhotoConfiguration default].maxEditVideoTime = 300;
    [ZLPhotoConfiguration default].cameraConfiguration.sessionPreset = CaptureSessionPresetVga640x480;
    [ZLPhotoConfiguration default].cameraConfiguration.videoExportType = VideoExportTypeMp4;
    
    NSMutableArray *phos = [NSMutableArray array];
    for (int i = 0; i<self.photos.count; i++) {
         
        if (![self.photos[i] isKindOfClass:[UIImage class]]) {
            
            [phos addObject: self.photos[i]  ];
 
        }
    }
   
    
    ZLPhotoPreviewSheet *ps = [[ZLPhotoPreviewSheet alloc] initWithSelectedAssets:phos ];
    
    ps.selectImageBlock = ^(NSArray<ZLResultModel *> *models, BOOL isOriginal) {
        NSMutableArray *photos = [[NSMutableArray alloc] init];
        [models enumerateObjectsUsingBlock:^(ZLResultModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [photos addObject:obj.asset];
        }];

        weakSelf.photos = photos;
        weakSelf.images = @[].mutableCopy;
        [weakSelf recursiveHandle:[NSMutableArray arrayWithArray:weakSelf.photos] isFullImage:YES];

        
//        [weakSelf recursiveHandle:photos isFullImage:isOriginal];
    };
    [ps showPhotoLibraryWithSender:self ];
    
    
    
    
}
- (void)onSaveBtn:(id)sender {
    [self.view endEditing:YES];
    WEAKSELF_ZM
    
    
    
    if (!weakSelf.images.count) {
         
        if (!self.textView.text.length) {
     
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = @"请输入内容!";
            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
            [hud hideAnimated:YES afterDelay:1.f];
            return;
        }
        
    }
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"加载中...";
    [hud showAnimated:YES];
//    /topic/sendTopic
    
    NSString *authToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
    NSString *userId = [WFCCNetworkService sharedInstance].userId;

    
//    [[WFCUConfigManager globalManager].appServiceProvider updateGroup:self.announcement.groupId announcement:self.textView.text success:^(long timestamp) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//            hud.mode = MBProgressHUDModeText;
//            hud.label.text = @"保存成功";
//            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
//            [hud hideAnimated:YES afterDelay:1.f];
//            
//            self.announcement.author = [WFCCNetworkService sharedInstance].userId;
//            self.announcement.text = self.textView.text;
//            self.announcement.timestamp = timestamp;
//            [self.navigationController popViewControllerAnimated:YES];
//        });
//    } error:^(int error_code) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//            hud.mode = MBProgressHUDModeText;
//            hud.label.text = @"保存失败";
//            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
//            [hud hideAnimated:YES afterDelay:1.f];
//        });
//    }];
    
    
//    NSMutableDictionary *content = [NSMutableDictionary dictionary];
//    if (self.textView.text.length) {
//         
//        [content setObject:self.textView.text forKey:@"text"];
//        
//    }
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSMutableArray *urls = [NSMutableArray array];
        __block NSString *errorMsg = nil;

        if (weakSelf.images.count) {
            
            for (UIImage *logFile in weakSelf.images) {
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
                
                
                NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/%@" , @"file/upload"];
                if (weakSelf.videoUrl) {
                     
                    url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/%@" , @"file/uploadVideo"];
                }
                dispatch_semaphore_t sema = dispatch_semaphore_create(0);
                
                __block BOOL success = NO;
                NSLog(@"url %@ ",url);
                
                [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                    
                     
                    
                    NSData *logData = UIImageJPEGRepresentation([weakSelf compressImage:logFile maxKB:150], 1);
                    if (!logData.length) {
                        logData = [@"empty" dataUsingEncoding:NSUTF8StringEncoding];
                    }
                    //save gif
                    UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
                    
                    NSString *filePath = [userId stringByAppendingString:[NSString stringWithFormat:@"img%lld.%@", recordTime,weakSelf.videoUrl?[weakSelf.videoUrl pathExtension]:@"jpg"]];
                    NSString *fileName = [[NSURL URLWithString:filePath] lastPathComponent];
//                    NSData *datas = [NSData dataWithContentsOfFile:weakSelf.desFileName];
                    if (weakSelf.videoUrl) {
                        NSError *error = nil;
                        BOOL ur = [formData appendPartWithFileURL:weakSelf.videoUrl name:@"file" fileName:filePath mimeType:[weakSelf mimeTypeOfFile:weakSelf.desFileName] error:&error];
                        NSLog(@" 1= %d ",ur);
                        
                    }else{
                        [formData appendPartWithFileData:logData name:@"file" fileName:fileName mimeType: @"image/jpeg"];
                    }
                    
                    
                } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    
                    NSDictionary *dict = (NSDictionary *)responseObject;

                    if ([responseObject isKindOfClass:[NSDictionary class]]) {
                        
                        if([dict[@"code"] intValue] == 200) {
                            NSLog(@"上传成功");
                            success = YES;
                            
                            if ([[dict handleNullObjectForKey:@"data"] handleNullObjectForKey:@"fullPath"]) {
                            https://t.yehuoim.com/user/upload/img/2024/06/01/y0gqmws2kgif1717249681982.jpg
                                [urls addObject:[[dict handleNullObjectForKey:@"data"] handleNullObjectForKey:@"fullPath"]];
                            }
                            //                        NSString *name = [logFile componentsSeparatedByString:@"/"].lastObject;
                            //                        [uploadedFiles removeObject:name];
                            //                        [uploadedFiles addObject:name];
                            //                        [urls addObject:nam]
                            NSLog(@"--- %@   urls %@ ", dict ,urls);
                            
                            //                        [[NSUserDefaults standardUserDefaults] setObject:uploadedFiles forKey:@"mars_uploaded_files"];
                            //                        [[NSUserDefaults standardUserDefaults] synchronize];
                            
 
                        }
                    }else{
                        errorMsg = [dict handleNullObjectForKey:@"msg"] ;

                    }
                    NSLog(@"---responseObject  %@     ", responseObject );

                    if (!success) {
                        errorMsg = @"服务器响应错误";
                    }
                    dispatch_semaphore_signal(sema);
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    NSLog(@"上传失败：%@", error);
                    dispatch_semaphore_signal(sema);
                    errorMsg = error.localizedFailureReason;
                    
                }];
                
                dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
                
                if (!success) {
                    NSLog(@"---  上传失败 "  );
//                    dispatch_sync(dispatch_get_main_queue(), ^{
//                       
//                        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//                        hud.mode = MBProgressHUDModeText;
//                        hud.label.text = @"上传失败";
//                        //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
//                        [hud hideAnimated:YES afterDelay:1.f];
//                        
//                        return;
//                    });
//                    errorBlock(errorMsg);
                    return;
                }
            }
            
            dispatch_sync(dispatch_get_main_queue(), ^{

                if (errorMsg) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                       
                        [hud hideAnimated:YES];

                        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                        hud.mode = MBProgressHUDModeText;
                        hud.label.text = @"上传失败";
                        //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                        [hud hideAnimated:YES afterDelay:1.f];
                        
                     });
                    return;
                    
                }
                NSLog(@"---  完成 "  );

                NSLog(@"---  下一步 "  );

                
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                manager.requestSerializer = [AFJSONRequestSerializer serializer];
                manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
                
                //在调用其他接口时需要把cookie传给后台，也就是设置cookie的过程

                if(authToken.length) {
                    [manager.requestSerializer setValue:authToken forHTTPHeaderField:@"authToken"];
            //    } else {
            //        NSData *cookiesdata = [self getAppServiceCookies];//url和登录时传的url 是同一个
            //        if([cookiesdata length]) {
            //            NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
            //            NSHTTPCookie *cookie;
            //            for (cookie in cookies) {
            //                [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
            //            }
            //        }
                }
                NSString *topicType = @"TEXT";
                NSString *location = @"";
                if (urls.count) {
                      
//                    [content setObject:urls forKey:@"imgList"];
                    topicType = @"IMAGE";
                    
                    if (weakSelf.videoUrl) {
                         
                        topicType = @"VIDEO";

                    }
                    
                    location = [urls componentsJoinedByString:@","];
                    
                }
//                if (urls.count) {
//                      
////                    [content setObject:urls forKey:@"imgList"];
//                    topicType = @"IMAGE";
//                    location = [urls jk_JSONString];
//                }
                
                //    [self.delegate locationDidSelect:locationPoint.coordinate locationName:locationPoint.title mapScreenShot:locationPoint.thumbnail];

                
                WEAKSELF_ZM
                NSDictionary *parameters = @{@"content":weakSelf.textView.text,@"openType":@(self.selectsT),@"userIdList":self.managerList.count?[self.managerList componentsJoinedByString:@","]:@[],@"location":location,@"topicType":topicType,@"longitude":self.locationPoint?@(self.locationPoint.coordinate.longitude):@0,@"latitude":self.locationPoint?@(self.locationPoint.coordinate.latitude):@0,@"address":self.locationPoint?self.locationPoint.title:@"" }; ///<.TEXT, IMAGE, VIDEO

                
                
                NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/%@" , @"topic/sendTopic"];
            //    {\"text\":\"文字内容\",\"imgList\":[\"http://111\",\"http://222\"],\"videoList\":[\"http:111\",\"http://222\"]}")
                [manager POST:url
                   parameters:parameters
                     progress:nil
                      success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [hud hideAnimated:YES];
                        NSDictionary *dic = responseObject;
                        NSLog(@" ret---  %@ ", dic );

                        if([dic[@"code"] intValue] == 200) {
                            
                            weakSelf.photos = @[].mutableCopy;
                            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                            hud.mode = MBProgressHUDModeText;
                            hud.label.text = @"发布成功";
                            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                            [hud hideAnimated:YES afterDelay:1.f];
                            hud.completionBlock = ^{
                                
                                [weakSelf.navigationController popViewControllerAnimated:YES];

                            };
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"postMeNetworking" object:nil userInfo:@{@"dic":@""}];

                            
                        }else{
                            [hud hideAnimated:YES];

                            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                            hud.mode = MBProgressHUDModeText;
                            hud.label.text = [dic handleNullObjectForKey:@"msg"];
                            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                            [hud hideAnimated:YES afterDelay:1.f];
                            
                        }

                        
                        
                        
                    });
             
                    
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                    if (error) {
                        
                        NSLog(@" ret---  %@ ", error );
                        
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [hud hideAnimated:YES];

                        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                        hud.mode = MBProgressHUDModeText;
                        hud.label.text = error.localizedDescription;
                        //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                        [hud hideAnimated:YES afterDelay:1.f];
                    });
                    
                }];
                
                
                
                
                
            });
            
        }
        

        
        
    });
    
  
    
}


- (NSString *)mimeTypeOfFile:(NSString *)filePath {
    NSString *fileExtension = [filePath pathExtension];
    NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtension, NULL);
    NSString *mimeType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
    return mimeType.length?mimeType:@"application/octet-stream";;
}
#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
//    [self updateMaxLengthLabel];
//    if ([self.announcement.text isEqualToString:textView.text]) {
//        self.navigationItem.rightBarButtonItem.enabled = NO;
//    } else {
//        self.navigationItem.rightBarButtonItem.enabled = YES;
//    }
    self.placeholderLabel.hidden = textView.text.length;

}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
    if(newText.length > 200) {
        [self.view makeToast:@"超过大小限制"];
        return NO;
    }
    
    return YES;
}






#define k_THUMBNAIL_IMG_WIDTH  120//缩略图及cell大小
#define k_FPS 1//一秒想取多少帧

//这本来是个异步调用，但写成这种方便大家看和复制来直接测试
- (UIImage*)getVideoThumbnailWithUrl:(NSURL*)videoUrl second:(CGFloat)second
{
    if (!videoUrl)
    {
        NSLog(@"WARNING:videoUrl为空");
        return nil;
    }
    AVURLAsset *urlSet = [AVURLAsset assetWithURL:videoUrl];
    AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlSet];
    imageGenerator.appliesPreferredTrackTransform = YES;
    imageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    /*
     如果不需要获取缩略图，就设置为NO，如果需要获取缩略图，则maximumSize为获取的最大尺寸。
     以BBC为例，getThumbnail = NO时，打印宽高数据为：1920*1072。
     getThumbnail = YES时，maximumSize为100*100。打印宽高数据为：100*55.
     注：不乘[UIScreen mainScreen].scale，会发现缩略图在100*100很虚。
     */
    BOOL getThumbnail = YES;
    if (getThumbnail)
    {
        CGFloat width = [UIScreen mainScreen].scale * 120;
        imageGenerator.maximumSize =  CGSizeMake(ZmScreenWidth_N(), ZmScreenHeight_N());
    }
    NSError *error = nil;
    CMTime time = CMTimeMake(second,k_FPS);
    CMTime actucalTime;
    CGImageRef cgImage = [imageGenerator copyCGImageAtTime:time actualTime:&actucalTime error:&error];
    if (error) {
        NSLog(@"ERROR:获取视频图片失败,%@",error.domain);
    }
    CMTimeShow(actucalTime);
    UIImage *image = [UIImage imageWithCGImage:cgImage];
    NSLog(@"imageWidth=%f,imageHeight=%f",image.size.width,image.size.height);
    CGImageRelease(cgImage);
    return image;
}

- (void)convertAvcompositionToAvasset:(AVComposition *)composition completion:(void (^)(AVAsset *asset))completion {
    // 导出视频
    AVAssetExportSession *exporter = [AVAssetExportSession exportSessionWithAsset:composition presetName:AVAssetExportPresetHighestQuality];
    // 生成一个文件路径
    NSInteger randNumber = arc4random();
    NSString *exportPath = [NSTemporaryDirectory() stringByAppendingString:[NSString stringWithFormat:@"%ldvideo.mov", randNumber]];
    NSURL *exportURL = [NSURL fileURLWithPath:exportPath];
    // 导出
    if (exporter) {
        exporter.outputURL = exportURL;  // 设置路径
        exporter.outputFileType = AVFileTypeQuickTimeMovie;
        exporter.shouldOptimizeForNetworkUse = YES;
        [exporter exportAsynchronouslyWithCompletionHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if (AVAssetExportSessionStatusCompleted == exporter.status) {   // 导出完成
                    NSURL *URL = exporter.outputURL;
                    AVAsset *avAsset = [AVAsset assetWithURL:URL];
                     if (completion) {
                        completion(avAsset);
                    }
                } else {
                    if (completion) {
                        completion(nil);
                    }
                }
            });
        }];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) {
                completion(nil);
            }
        });
    }
}
- (void)handleVideo:(NSURL *)url photos:(NSMutableArray<PHAsset *> *)photos isFullImage:(BOOL)isFullImage {
    AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil];
    AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
    generate1.appliesPreferredTrackTransform = YES;
    NSError *err = NULL;
    CMTime time = CMTimeMake(1, 2);
    CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
    UIImage *thumbnail = [[UIImage alloc] initWithCGImage:oneRef];
    if (thumbnail) {
         
        thumbnail = [WFCCUtilities generateThumbnail:thumbnail withWidth:thumbnail.size.width withHeight:thumbnail.size.height];

//        [self.images addObject:thumbnail];
        self.images = @[thumbnail].mutableCopy;
    }
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];

    NSString *CompressionVideoPaht = [WFCCUtilities getDocumentPathWithComponent:@"/VIDEO"];
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:@"AVAssetExportPresetMediumQuality"];

    NSDateFormatter *formater = [[NSDateFormatter alloc] init];// 用时间, 给文件重新命名, 防止视频存储覆盖,

    [formater setDateFormat:@"yyyy-MM-dd_HH-mm-ss"];

    NSFileManager *manager = [NSFileManager defaultManager];

    BOOL isExists = [manager fileExistsAtPath:CompressionVideoPaht];
    if (!isExists) {
         [manager createDirectoryAtPath:CompressionVideoPaht withIntermediateDirectories:YES attributes:nil error:nil];
     }
//
    NSString *resultPath = [CompressionVideoPaht stringByAppendingPathComponent:[NSString stringWithFormat:@"outputJFVideo-%@.mov", [formater stringFromDate:[NSDate date]]]];

    NSLog(@"resultPath = %@",resultPath);

    exportSession.outputURL = [NSURL fileURLWithPath:resultPath];

    exportSession.outputFileType = AVFileTypeMPEG4;

    exportSession.shouldOptimizeForNetworkUse = YES;

    CMTime time2 = [asset1 duration];
    int seconds = ceil(time2.value/time2.timescale);
    
    __weak typeof(self)ws = self;

   
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     {
         if (exportSession.status == AVAssetExportSessionStatusCompleted) {
             NSData *data = [NSData dataWithContentsOfFile:resultPath];
             float memorySize = (float)data.length / 1024 / 1024;
             NSLog(@"视频压缩后大小 %f", memorySize);
             dispatch_async(dispatch_get_main_queue(), ^{
                 [MBProgressHUD hideHUDForView:ws.view animated:YES];
//                 [ws.delegate videoDidCapture:resultPath thumbnail:thumbnail duration:seconds];
                 
             });
             
             ws.videoUrl = [NSURL fileURLWithPath:resultPath];

             [ws recursiveHandle:photos isFullImage:isFullImage];
         } else {
             dispatch_async(dispatch_get_main_queue(), ^{
                 [MBProgressHUD hideHUDForView:ws.view animated:YES];
//                 [self.view makeToast:@"视频处理失败" duration:1 position:CSToastPositionCenter];
                 
             });
             NSLog(@"压缩失败");
         }

     }];
}
- (void)recursiveHandle:(NSMutableArray<PHAsset *> *)photos isFullImage:(BOOL)isFullImage {
    __weak typeof(self) weakself = self;

    if (photos.count == 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:weakself.view animated:YES];
            [weakself reloadImagesViews];

        });
        
    }else{
        PHAsset *phAsset = photos[0];
        [photos removeObjectAtIndex:0];
        if ([phAsset isKindOfClass:[UIImage class]]) {
            
            [weakself.images addObject: phAsset  ];
 
            
            [weakself recursiveHandle:photos isFullImage:isFullImage];
            return;
        }
        if (phAsset.mediaType == PHAssetMediaTypeVideo) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showHUDAddedTo:weakself.view animated:YES];
                [MBProgressHUD HUDForView:weakself.view].mode = MBProgressHUDModeDeterminate;
                [MBProgressHUD HUDForView:weakself.view].label.text = WFCString(@"Processing");
            });
            
            
            PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
            options.networkAccessAllowed = YES;
            options.version = PHImageRequestOptionsVersionCurrent;
            options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
            
            PHImageManager *manager = [PHImageManager defaultManager];
            [manager requestAVAssetForVideo:phAsset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {

                if ([asset isKindOfClass:[AVComposition class]]) {
                    [weakself convertAvcompositionToAvasset:(AVComposition *)asset completion:^(AVAsset *asset) {
                        AVURLAsset *urlAsset = (AVURLAsset *)asset;
                        [weakself handleVideo:urlAsset.URL photos:photos isFullImage:isFullImage];
                    }];
                } else {
                    AVURLAsset *urlAsset = (AVURLAsset *)asset;
                    [weakself handleVideo:urlAsset.URL photos:photos isFullImage:isFullImage];
                }
                
                
            }];
        } else if(phAsset.mediaType == PHAssetMediaTypeImage) {
            PHImageRequestOptions *imageRequestOption = [[PHImageRequestOptions alloc] init];
            imageRequestOption.networkAccessAllowed = YES;
            PHCachingImageManager *cachingImageManager = [[PHCachingImageManager alloc] init];
            cachingImageManager.allowsCachingHighQualityImages = NO;
            [cachingImageManager
             requestImageDataForAsset:phAsset
             
             options:imageRequestOption
             
             resultHandler:^(NSData *_Nullable imageData, NSString *_Nullable dataUTI,
                                                                   UIImageOrientation orientation, NSDictionary *_Nullable info) {
                   BOOL downloadFinined = (![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey] && ![[info objectForKey:PHImageResultIsDegradedKey] boolValue]);
                   if (downloadFinined) {
                       
//                       [UIImage imageWithData:imageData]
                       
                       
//                       if ([weakself isGifWithImageData:imageData] && [weakself respondsToSelector:@selector(gifDidCapture:)]) {
//                           [weakself gifDidCapture:imageData];
//                       } else if ([weakself respondsToSelector:@selector(imageDidCapture:fullImage:)]) {
//                           [weakself imageDidCapture:[UIImage imageWithData:imageData] fullImage:isFullImage];
//                       }
                       
                       
                       [weakself.images addObject: [UIImage imageWithData:UIImageJPEGRepresentation([UIImage imageWithData:imageData], 0.5)] ];
                       
                       
                       
                       [weakself recursiveHandle:photos isFullImage:isFullImage];
                       
                   }

                   if ([info objectForKey:PHImageErrorKey]) {
                       [weakself.view makeToast:@"下载图片失败"];
                       [weakself recursiveHandle:photos isFullImage:isFullImage];
                   }
                                                       
            }];
        }
        
    }
        
}

- (BOOL)isGifWithImageData: (NSData *)data {
    if ([[self contentTypeWithImageData:data] isEqualToString:@"gif"]) {
        return YES;
    }
    return NO;
}

- (NSString *)contentTypeWithImageData: (NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];
    switch (c) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";
        case 0x47:
            return @"gif";
        case 0x49:
        case 0x4D:
            return @"tiff";
        case 0x52:
            if ([data length] < 12) {
                return nil;
            }
            
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                return @"webp";
            }
            return nil;
    }
    return nil;
}



@end
